<?php
App::uses('AppController', 'Controller');
/**
 * Apoiadores Controller
 *
 * @property Apoiadore $Apoiadore
 */
class GeonamesController extends GeonamesAppController {
	
	public function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->allow('paises', 'estados', 'cidades');
	}
	
	public function paises(){
		$query = $this->request->query['query'];
		$this->autoRender = false;
		$this->loadModel('Geonames.Pais');
		if(Configure::read('Config.language') == 'pt-br')
			$lang = 'pt';
		else $lang = Configure::read('Config.language');
		$dados = $this->Pais->find('all', array('conditions'=>array('language'=> 'pt', 'LOWER(countryName) LIKE'=>"%".strtolower($query)."%"), 'fields'=>array('geonameId', 'countryName', 'id')));
		//$dados = $this->Pais->find('all', array('conditions'=>array('language'=> 'pt', 'LOWER(countryName) LIKE'=>"%".strtolower($query)."%"), 'fields'=>array('countryName')));
		foreach($dados as $item){
			$return[] = $item['Pais'];
		}
		if(isset($return))
			return json_encode($return);
		return false;
	}
	
	private function finder($model){
		$query = $this->request->query['query'];
		$parentId = $this->request->query['parentId'];
		$this->loadModel('Geonames.'.$model);
		if(Configure::read('Config.language') == 'pt-br')
			$lang = 'pt';
		else $lang = Configure::read('Config.language');
		$dados = $this->$model->find('all',
			array(
				'conditions'=>array(
					'language'=> 'pt',
					'LOWER(name) LIKE'=>"%".strtolower($query)."%",
					'geonameParentId'=>$parentId
				),
				'fields'=>array(
					'geonameId', 'name', 'id'
				)
			)
		);
		foreach($dados as $item){
			$return[] = $item[$model];
		}
		if(isset($return))
			return json_encode($return);
		return false;
	}
	
	public function estados(){
		$model = 'RegiaoAdministrativa';
		$this->autoRender = false;
		return $this->finder($model);
	}
	
	public function cidades(){
		$model = 'Cidade';
		$this->autoRender = false;
		return $this->finder($model);
	}
	
}